<?php
/*
 * @Author: lokei
 * @Date: 2022-08-08 22:55:21
 * @LastEditors: lokei
 * @LastEditTime: 2022-10-08 12:34:41
 * @Description: 
 */

namespace App\Http\Controllers\Rbac\Auth;

use App\Common\Tools\ResultTool;
use App\Http\Controllers\Controller;
use App\Models\Platform\ConfMpModel;
use App\Models\Ucenter\FansModel;
use App\Models\Ucenter\UserModel;
use App\Services\Ucenter\FansService;
use App\Services\Ucenter\UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

use GuzzleHttp;

class MpController extends Controller
{

    private UserService $user_service;

    private FansService $fans_service;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
        $this->user_service = new UserService();
        $this->fans_service = new FansService();
    }

    //

    public function code(Request $request)
    {
        $conf = ConfMpModel::first();
        $http = new GuzzleHttp\Client;
        $params = [
            'appid' => $conf->appid,
            'secret' => $conf->secret,
            'code' => $request->code,
            'grant_type' => 'authorization_code'
        ];
        $response = $http->get('https://api.weixin.qq.com/sns/oauth2/access_token', [
            'query' => $params
        ]);
        $result = json_decode($response->getBody(), true);
        if (array_key_exists('errcode', $result) && $result['errcode'] != 0) {
            $res = ResultTool::fail();
            $res['errorCode'] = $result['errcode'];
            $res['errorMsg'] = $result['errmsg'];
            return $res;
        }
        if (array_key_exists('openid', $result) && $result['openid'] != '') {
            $fans = FansModel::where('openid', '=', $result['openid'])->where('platform', '=', 'mp')->first();
            if (!is_null($fans)) {
                if (!($fans->uid > 0)) {
                    $uid = $this->user_service->createUser();
                    $fans->uid = $uid;
                    $fans->save();
                }
            } else {
                $this->fans_service->registerOpenid('mp', $result['openid']);
                $fans = FansModel::where('openid', '=', $result['openid'])->first();
                $uid = $this->user_service->createUser();
                $fans->uid = $uid;
                $fans->save();
            }
            $user = UserModel::where('uid', '=', $fans->uid)->first();
            $token = Auth::login($user);
            $res = ResultTool::success();
            $res['data']['token'] = $token;
            return $res;
        }
        $res = ResultTool::fail();
        $res['errorMsg'] = '微信公众号用户登入失败！';
        return $res;
    }
}
